<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户聊天室</title>
    <style>
        #content{
            overflow: auto;
        }
    </style>
</head>
<body>
<textarea id="content" rows="20" cols="40"></textarea><br>
客户:<input type="text"/>
<button>发送</button>
<script>
    var content = document.getElementById("content")
    var sendInput = document.getElementsByTagName("input")[0]
    var btn = document.getElementsByTagName("button")[0];
    var ws = null;
    if ('WebSocket' in window){//这里的判断是判断websocket是否可以在windows使用
        //在使用websocket的时候，我们首先新建一个WebSocket实例
        ws = new WebSocket("ws:192.168.0.7:8000/MyServer");
    }else {
        alert("浏览器不支持");
    }

    //建立连接回调
    ws.onopen = function(){
        content.text = "\n成功连接到服务器";
    }

    //连接断开回调
    ws.onclose = function () {
        content.text = "\n连接已断开";
    }

    //收到消息回调
    ws.onmessage = function (event) {
        console.log(event);
        content.innerHTML += "\n"+event.data;
    }

    //出错回调
    ws.onerror = function () {
        console.log("出错了")
    }

    //点击按钮发送消息
    btn.onclick = function () {
        var message = sendInput.value;
        if(message != ""){
            ws.send("客户:"+message);
        }
    }

    //窗口关闭，断开连接
    window.onclose = function () {
        ws.close();
    }
</script>
</body>
</html>